package com.generictimebox;

import java.util.ArrayList;

public class TimeBoxManager {
	
	private static volatile TimeBoxManager instance = null;
	private ArrayList<TimeBox> timeBoxes = new ArrayList<TimeBox>();
	
	private TimeBoxManager(){
		super();
	}
	
	public void init(){
		
		timeBoxes = new ArrayList<TimeBox>();

				
		timeBoxes.add(new TimeBox("T1", 5));
		timeBoxes.add(new TimeBox("T2", 5));
		timeBoxes.add(new TimeBox("T3", 5));
		
		
		
		/*
		timeBoxes.add(new TimeBox("Ready ? (10s)", 10));
		
		timeBoxes.add(new TimeBox("TimeBox 1 (30s)", 30));
		timeBoxes.add(new TimeBox("Pause 1 (10s)", 10));

		timeBoxes.add(new TimeBox("TimeBox 2 (30s)", 30));
		timeBoxes.add(new TimeBox("Pause 2 (10s)", 10));

		timeBoxes.add(new TimeBox("TimeBox 3 (30s)", 30));
		timeBoxes.add(new TimeBox("Pause 3 (10s)", 10));

		timeBoxes.add(new TimeBox("TimeBox 4 (30s)", 30));
		timeBoxes.add(new TimeBox("Pause 4 (10s)", 10));
*/
		
		
		
	}
	
	//singleton
    public final static TimeBoxManager getInstance() {
       
    	if (TimeBoxManager.instance == null) {
          synchronized(TimeBoxManager.class) {
             if (TimeBoxManager.instance == null) {
            	 TimeBoxManager.instance = new TimeBoxManager();
            	 TimeBoxManager.instance.init();
             }
           }
        }
        return TimeBoxManager.instance;
    }
    
    public void setTimeBoxes(ArrayList<TimeBox> newTimeBoxes){
    	
    	this.timeBoxes = newTimeBoxes;
    }

    public ArrayList<TimeBox> getTimeBoxes(){
    	
    	return TimeBoxManager.instance.timeBoxes;
    	
    }

    public int getDuration(){
    	
    	int result = 0;
    	for(TimeBox timebox : this.timeBoxes){
    		result = result + timebox.getDuration();
    	}
    	
    	return result;
    }
    
    public String getStepNameAt(long moment){
    	
    	moment = this.getDuration() - moment;
    	int count = 0;
    	String result = "";
    	
    	for(TimeBox timebox : this.timeBoxes){
    		
    		if(moment >= count && moment <= count + timebox.getDuration()){
    			
    			result = timebox.getStepName();
    		}
    		
    		count = count + timebox.getDuration();
    	
    	}
    	
    	
    	return result;
    }
    
    public TimeBox getTimeBoxAt(long moment){
    	
    	moment = this.getDuration() - moment;
    	int count = 0;
    	TimeBox result = new TimeBox();
    	
    	for(TimeBox timebox : this.timeBoxes){
    		
    		if(moment >= count && moment <= count + timebox.getDuration()){
    			
    			result = timebox;
    		}
    		
    		count = count + timebox.getDuration();
    	
    	}
    	
    	
    	return result;
    }
}
